<template>
    <el-dialog v-model="AddToOrder" title="Add to Order" draggable width="78%"
        style="position: absolute;top:0px;left:0;right:0; height:69vh;">
        <div class="flex addOrder">
            <div class="flex fdc addLeft brs bs pt-10 pl-10 pr-10 pb-5">
                <el-select v-model="rqfValut" @input="getRfq" @change="rfqInfo" @visible-change="visibleRfq" filterable
                    placeholder="Please select an inquiry" style="width: 25%;">
                    <el-option v-for="item in rfqList" :key="item.inquiry_id" :label="item.inquiry_id"
                        :value="item.inquiry_id" />
                </el-select>

                <div class="flex jc-sb aic mt-10">
                    <p class="f16">Add items to order</p>
                    <el-button class="add" type="primary" plain @click="add">Add</el-button>
                </div>

                <div class="mt-10">
                    <el-table ref="multipleTableRef" :data="leftList" height="49vh" style="width: 100%;"
                        @selection-change="handleSelectionChange">
                        <el-table-column type="selection" min-width="30" />
                        <el-table-column property="product.model" align="center" label="MODEL" min-width="140" />
                        <el-table-column property="brand.brand_name" align="center" label="BRAND" />
                        <el-table-column property="purchaser_id_list" align="center" label="BUYER" min-width="100" />
                        <el-table-column property="Qty" align="center" label="Qty" min-width="60" />
                        <el-table-column property="item.quotation_price" align="center" label="PRICE" min-width="90" />
                        <el-table-column property="item.leadingtime" align="center" label="LEADING" min-width="90" />
                        <el-table-column property="item.product_condition" align="center" label="CONDITION"
                            min-width="110" />
                    </el-table>
                </div>
            </div>
            <!-- 右边 -->
            <div class="addRight bs brs pl-10 pt-10 pr-10 ">
                <div class="flex jc-sb">
                    <div>
                        <el-button type="primary" @click="New" plain class="new">New</el-button>
                        <el-button type="primary" @click="save" plain class="new">Save</el-button>
                        <el-button @click="Delete" type="primary">Delete</el-button>
                    </div>
                    <el-select v-model="PI_name" @input="getOrder" @change="orderInfo" @visible-change="visibleOrder"
                        filterable :disabled="order" placeholder="Please select the order">
                        <el-option v-for="item in orderList" :key="item.PI_name" :label="item.PI_name"
                            :value="item.order_id" />
                    </el-select>
                </div>
                <div class="mt-10 w100p">
                    <el-table :data="rightList" @row-click="row" @selection-change="selectionRightList" height="53.4vh"
                        style="width: 100%">
                        <el-table-column type="selection" min-width="30" />
                        <el-table-column align="center" label="MODEL" min-width="180">
                            <template v-slot="model">
                                <el-select v-model="model.row.product_name_pi" @input="getModel" @change="changeModel"
                                    @visible-change="visible" filterable placeholder="MODEL">
                                    <el-option v-for="item in newModel" :key="item.label" :label="item.label"
                                        :value="item.id" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="BRAND" min-width="120">
                            <template v-slot="brand">
                                <el-select v-model="brand.row.Brand_name" @input="getBrand" @visible-change="visible"
                                    filterable placeholder="BRAND">
                                    <el-option v-for="item in newBrand" :key="item.label" :label="item.label"
                                        :value="item.id" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="QTY" min-width="80">
                            <template v-slot="qty">
                                <el-input v-model="qty.row.quantity" />
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="PRICE" min-width="90">
                            <template v-slot="price">
                                <el-input v-model="price.row.price" />
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="LEADING" min-width="125">
                            <template v-slot="leading">
                                <el-select v-model="leading.row.leadingtime" filterable placeholder="LEADING">
                                    <el-option v-for="item in newLeading" :key="item.label" :label="item.label"
                                        :value="item.case" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" label="CONDITION" min-width="150">
                            <template v-slot="condition">
                                <el-select v-model="condition.row.product_condition" filterable placeholder="CONDITION">
                                    <el-option v-for="item in newCondition" :key="item.label" :label="item.label"
                                        :value="item.case" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <!-- <el-table-column align="right">
                            <template v-slot="del">
                                <el-button @click="Delete(del.row)" size="small" type="primary">Delete</el-button>
                            </template>
                        </el-table-column> -->
                    </el-table>
                </div>
            </div>
        </div>
    </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import * as $axios from '../../../../api/index'
import { ElMessage } from 'element-plus'
import { useDemoStore } from '../../../../pinia/index'
const store = useDemoStore()

defineProps({
    newLeading: Array,
    newCondition: Array
})


// 添加订单弹窗
const AddToOrder = ref(false)
const open = () => {
    AddToOrder.value = true
}
// 把open暴露给父组件
defineExpose({
    open
})

// 打开关闭选择框触发
const visible = () => {
    inpLeftOrder.value = '' //清空输入框
    inpModel.value = ''
    textBrand.value = ''
}

const visibleRfq = () => {
    inpOrder.value = ''  //清空输入框
    getRfq()
}

// 获取询盘列表
const rqfValut = ref('')
const rfqList = ref([])
const inpOrder = ref('')
const getRfq = (value) => {
    if (value) {
        if (value.data != null) {
            inpOrder.value += value.data
        } else if (value.data == null) {
            inpOrder.value = inpOrder.value.slice(0, -1)
        }
    }
    const data = {
        token: store.token,
        keywords: inpOrder.value
    }
    $axios.$orderGet_inquiry_by_key(data).then(res => {
        rfqList.value = res.data.data
        // console.log(rfqList.value)
    })
}


// 获取询盘信息
const leftList = ref([])
const rightList = ref([])
const storeValie = ref('')
const PI_name = ref('')
const order_id = ref('')
const rfqInfo = (value) => {
    storeValie.value = value || storeValie.value
    const data = {
        token: store.token,
        inquiry_id: storeValie.value
    }
    $axios.$orderGet_inquiry_info(data).then(res => {
        leftList.value = res.data.inquiryItem   //左边列表数据
        rightList.value = res.data.orderInfo.itemOrder  //右边列表数据
        rightList.value.push([])
        PI_name.value = res.data.orderInfo.PI_name
        order_id.value = res.data.orderInfo.order_id
        order.value = false
        // console.log(order_id.value)
    })
}

// 左边多选框
const inquiry_item_info_id = ref([])
const handleSelectionChange = (value) => {
    inquiry_item_info_id.value = []
    value.forEach(item => {
        inquiry_item_info_id.value.push(item.item.inquiry_item_info_id)
    });
    console.log(value)
}

// 添加到右边
const add = () => {
    const data = {
        token: store.token,
        inquiry_item_info_id: inquiry_item_info_id.value
    }
    $axios.$production_item(data).then(res => {
        rightList.value.pop()
        rightList.value = [
            ...rightList.value,
            ...res.data
        ]
        rightList.value.push([])
        // console.log(res)
        console.log(rightList.value)
    })
}

const row = (data) => {
    console.log(data)
}


// model
const newModel = ref([])
const inpModel = ref('')
var timer
const getModel = (text) => {
    if (text.data != null) {
        inpModel.value += text.data
    } else if (text.data == null) {
        inpModel.value = inpModel.value.slice(0, -1)
    }
    const data = {
        token: store.token,
        keywords: inpModel.value
    }
    clearTimeout(timer);
    timer = setTimeout(() => {
        $axios.$product_find(data).then(res => {
            console.log(res.data)
            newModel.value = res.data.map(item => {
                return {
                    'label': item.model,
                    'id': item.product_id
                }
            })
        })
    }, 300)
}

// brand
const newBrand = ref([])
const textBrand = ref('')
var timer
const getBrand = (text) => {
    if (text.data != null) {
        textBrand.value += text.data
    } else if (text.data == null) {
        textBrand.value = textBrand.value.slice(0, -1)
    }
    const data = {
        token: store.token,
        keywords: textBrand.value
    }
    clearTimeout(timer);
    timer = setTimeout(() => {
        $axios.$product_brand(data).then(res => {
            console.log(res.data)
            newBrand.value = res.data.map(item => {
                return {
                    'label': item.brand_name,
                    'id': item.brand_id
                }
            })
        })
    }, 300)
}


// 订单列表选项框打开关闭触发
const visibleOrder = () => {
    inpLeftOrder.value = ''
    getOrder()
}

// 获取订单列表
const orderList = ref([])
const inpLeftOrder = ref('')
const getOrder = (value) => {
    if (value) {
        if (value.data != null) {
            inpLeftOrder.value += value.data
        } else if (value.data == null) {
            inpLeftOrder.value = inpLeftOrder.value.slice(0, -1)
        }
    }
    const data = {
        token: store.token,
        keywords: inpLeftOrder.value
    }
    $axios.$orderOrder_listo(data).then(res => {
        orderList.value = res.data.data
        console.log(res.data.data)
    })
}

// 选择订单
const orderInfo = (value) => {
    rightList.value.forEach(item => {
        order_id.value = value
        item.order_id = value
    })
    // console.log(rightList.value)
}


// 右边多选框
const order_info_id = ref([])
const selectionRightList = (value) => {
    order_info_id.value = value.map(item => {
        return item.order_info_id
    })
}


// 删除
const Delete = () => {
    // console.log(value)
    if (order_info_id.value.length > 0) {
        const data = {
            token: store.token,
            order_id_list: order_info_id.value
        }
        $axios.$orderDel_order(data).then(res => {
            console.log(res)
            rfqInfo()
            ElMessage({
                message: 'successfully delete',
                type: 'success',
            })
        })
    } else {
        ElMessage({
            message: 'Please choose',
            type: 'warning',
        })
    }
}

// 新建
const order = ref(false)
const New = () => {
    // console.log(rqfValut.value)
    if (rqfValut.value) {
        rightList.value = []
        PI_name.value = ''
        order.value = true
        for (let i = 0; i < 5; i++) {
            rightList.value.push({
                "msg": 1
            })
        }
    } else {
        ElMessage({
            message: 'Please select an inquiry',
            type: 'warning',
        })
    }
}


// 选择最后一个model时创建空白表单
const changeModel = () => {
    // console.log(rightList.value)
    const model = rightList.value[rightList.value.length - 1].product_name_pi
    console.log(model)
    if (model) {
        rightList.value.push([])
    }
}

// 保存
const save = () => {
    const product = ref([])
    // console.log(rqfValut.value)
    const saveData = ref([])
    rightList.value.forEach(data => {
        if (data.product_name_pi) {
            saveData.value.push(data)
        }
        // console.log(data)
    })
    product.value = saveData.value.map(item => {
        return {
            "order_id": item.order_id || order_id.value,
            "order_info_id": item.order_info_id ? item.order_info_id : '',
            "product_id": typeof item.product_name_pi == 'string' ? item.product_id : item.product_name_pi,
            "brand": item.Brand_name,
            "brand_id": typeof item.Brand_name == 'string' ? item.Brand_id : item.Brand_name,
            "inquiry_id": rqfValut.value,
            "purchaser_id": item.Purchaser_id ? item.Purchaser_id : '',
            "inquiry_item_info_id": item.inquiry_item_purchase_price_id ? item.inquiry_item_purchase_price_id : '',
            "model": item.product_name_pi,
            "qty": item.quantity,
            "price": item.price,
            "leadingtime": item.leadingtime,
            "product_condition": item.product_condition,
        }
    })


    console.log(product.value)
    // console.log(rightList.value)
    console.log(order_id.value)
    if (rightList.value[0].msg === 1) {  //新增
        const data = {
            token: store.token,
            product: product.value
        }
        $axios.$orderNew_order(data).then(res => {
            if (res.Status === 0) {
                rfqInfo()
                order.value = false
                ElMessage({
                    message: 'Successful preservation',
                    type: 'success',
                })
            }
            // console.log(res)
        })
    } else if (!!order_id.value) {  //没有order_id就是没有选择订单，提示选择订单

        const data = {
            token: store.token,
            product: product.value
        }
        $axios.$orderSave_order(data).then(res => {
            if (res.Status === 0) {
                rfqInfo()
                ElMessage({
                    message: 'Successful preservation',
                    type: 'success',
                })
            }
            // console.log(res)
        })
    }
    else {
        ElMessage({
            message: 'Please select the order',
            type: 'warning',
        })
    }

}

</script>

<style lang="less" scoped>
.addOrder {
    width: 100%;

    .brs {
        border-radius: 10px;
    }

    .addLeft {
        width: 47.5%;
    }

    .addRight {
        // padding-left: 10px;
        margin-left: 10px;
        width: 52%;

        .orderDetails:hover .delete {
            visibility: visible;
        }

        .delete {
            visibility: hidden;
        }
    }

    .add.el-button.is-plain {
        border: 1px solid #7da3f3;
        color: #7da3f3;
        background-color: #ecf5ff;
    }

    .new.el-button.is-plain {
        border: 1px solid #7da3f3;
        color: #7da3f3;
        background-color: rgb(255, 255, 255);
    }

}
</style>